package org.example.controller;

import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/s/*")
@Order(1)
public class controller1 implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException{
        System.out.println("我是过滤器初始化程序");
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain) throws IOException,ServletException{
        HttpServletRequest httpRequest=(HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse=(HttpServletResponse) servletResponse;
        String vStr=servletRequest.getParameter("permission");
        int permission=vStr==null?-1:Integer.parseInt(vStr);
        if(permission<5){
            httpResponse.setHeader("Content-type","text/html;charset=HTF-8");
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.getWriter().println("您的请求已被阻挡");
            System.out.println("已阻挡：权限等级是"+permission+"的请求："+httpRequest.getRequestURL());
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
        System.out.println("已放行：权限等级是"+permission+"的请求"+httpRequest.getRequestURI());
    }
    @Override
    public void destroy(){
        System.out.println("我是过滤器销毁程序");
    }
}
